package com.sike.netty.jinjie.codec.protocol;


import com.sike.netty.jinjie.codec.protocol.encoder.JsonStringToByteEncoder;
import com.sike.netty.jinjie.codec.protocol.encoder.ObjectToJsonEncoder;
import com.sike.netty.jinjie.codec.protocol.message.ChatMessage;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

public class Client2 {
    public static void main(String[] args) {
        new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {

                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new LoggingHandler(LogLevel.DEBUG));
                        ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024,5,4,0,0));
                        ch.pipeline().addLast(new JsonStringToByteEncoder());
                        ch.pipeline().addLast(new ObjectToJsonEncoder());
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter(){
                             @Override
                             public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                 for(int i = 1 ; i <= 500 ; i++) {
                                     ChatMessage chatMessage = new ChatMessage("hello, boy!!!--" + i);
                                     ctx.writeAndFlush(chatMessage);
                                 }
                             }
                         });
                    }
                }).connect("127.0.0.1",8081);
    }
}
